<template>
  <div class="dnnConfig_container">
    <MCard>
                <template #header>
                  <div class="title_box">
                    <!-- <img :src="networkAccessManagementBg2" alt=""> -->
                    <span class="text-14px">{{ t('functionService.apn_config_label') }}</span>
                  </div>
                </template>
                <div class="container_left_bottom_content p-l-15px p-t-20px p-r-10px">
                <el-form
                :inline="true"
                ref="appConfigRef"
                :model="apnConfig"
                :rules="appConfigFormRules"
                hide-required-asterisk
                >
                  <el-form-item  label="apn" class="tech-form-item" prop="apn">
                    <el-input v-model="apnConfig.apn" />
                  </el-form-item>
                  <el-form-item  label="apnId" class="tech-form-item" prop="apnId">
                    <el-input v-model="apnConfig.apnId" />
                  </el-form-item>
                  <el-form-item class="tech-form-item">
                    <div class="global_btn" v-globalLoading="addApnConfig" >                 
                      <el-icon class="m-r-5px"><Plus /></el-icon>
                      {{ t('functionService.add_apn_label') }}
                    </div>
                  </el-form-item>
                </el-form>                 
                </div>
                <div class="m-t-30px">
                  <el-table :data="appConfigList" max-height="150px">
                    <el-table-column label="apn" prop="apn" />
                    <el-table-column label="apnId" prop="id" />
                    <el-table-column label="操作">
                      <template #default="scope">
                        <div class="global_btn" v-globalLoading="deleteApnConfig.bind(null,scope.row)">
                          <el-icon class="m-r-5px"><Delete /></el-icon>
                          {{ t('functionService.delete_apn_label') }}
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </MCard>
    <el-card>
      <template #header>
        <div class="flex justify-between w-100%">
          <span>{{t('networkConfig.business_setting_label')}}</span>
          <!--  <div class="global_btn" @click="handleAddDnn">
            {{t('networkConfig.addDnn_label')}}
           </div> -->
        </div>
      </template>
      <el-table :data="dnnInfoList">
        <el-table-column :label="t('networkConfig.business_number_label')"  >
            <template v-slot="{row}">
              <span>{{ t('networkConfig.business_label') + (Number(row.id)) }}</span>
            </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.business_name_label')" >
          <template v-slot="{row}">
            <span>{{ TYPE_MAP[row.type] }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.switch_status_label')" > 
          <template v-slot="{row}">
            <span>{{ row.dnn_status === 'on' ? t('networkConfig.yes_label') : t('networkConfig.no_label') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.connection_mode_label')" >
          <template v-slot="{row}">
            <span>{{ row.connectionMode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="DNN" prop="using_dnn" />
        <el-table-column :label="t('networkConfig.enable_dhcp_label')" >
          <template v-slot="{row}">
            <span>{{ row.dhcp_status === 'on' ? t('networkConfig.yes_label') : t('networkConfig.no_label') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('networkConfig.enable_nat_label')" >
          <template v-slot="{row}">
            <span>{{ row.nat_status === 'on' ? t('networkConfig.yes_label') : t('networkConfig.no_label') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="VLAN" >
          <template v-slot="{row}">
            <span>{{ row.vlan_id }}</span>
          </template>
        </el-table-column>
        <!-- 端口选择 -->
        <el-table-column :label="t('networkConfig.selected_port_label')" >
          <template v-slot="{row}">
            <span>{{ row.portList.join(',') }}</span>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column :label="t('networkConfig.operation_label')" >
          <template v-slot="{row}">
             <div class="flex  gap-20px">
              <div class="global_btn" @click="handleEditDnn(row)">
                {{t('networkConfig.edit_label')}}
              </div>
             </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <Dialog 
    v-bind="dnnDialogConfig" 
    v-model:dialogVisible="dnnDialogConfig.visible"
    >
      <template #content>
        <div class="p-20px">
         <el-form ref="editDnnFormRef" :model="editDnnForm" :rules="editDnnFormRules" label-width="auto" label-position="left">
            <!-- 开关状态 -->
            <el-form-item :label="t('networkConfig.switch_status_label')">
              <el-switch active-value="on" inactive-value="off" v-model="editDnnForm.dnn_status" />
            </el-form-item>
            <!-- 开启DHCP -->
            <el-form-item :label="t('networkConfig.enable_dhcp_label')">
              <el-switch active-value="on" inactive-value="off" :disabled="isLocalMode()" v-model="editDnnForm.dhcp_status" />
            </el-form-item>
            <!-- 开启NAT -->
            <el-form-item :label="t('networkConfig.enable_nat_label')">
              <el-switch active-value="on" inactive-value="off" :disabled="isLocalMode() || setNatDisabled()" v-model="editDnnForm.nat_status" />
            </el-form-item>
            <el-form-item label="using_dnn配置">
              <MSelect v-model="editDnnForm.using_dnn" v-bind="apnOptionsConfig" />
            </el-form-item>
            <!-- vlan_id -->
            <el-form-item label="VLAN ID" prop="vlan_id">
              <el-input-number style="width: 150px;" :disabled="isLocalMode()" v-model.number="editDnnForm.vlan_id" :min="1" :max="4094" />
            </el-form-item>
            <!-- 端口配置 -->
            <el-form-item :label="t('networkConfig.port_config_label')">
               <el-checkbox-group v-model="editDnnForm.portList" :disabled="isLocalMode()">
                <el-checkbox v-for="item in [1, 2, 3]" :key="item" :label="item" border>
                  {{ 'Port ' + item }}
                </el-checkbox>
               </el-checkbox-group>
            </el-form-item>
            <!-- 按钮 -->
         </el-form>
        </div>
      </template>
      <template #footer>
        <div class="flex gap-20px justify-center w-100% ">
          <div class="global_btn" style="width: 100px;" v-globalLoading="saveEditDnn">{{ t('networkConfig.save_label') }}</div>
          <div class="global_btn" style="width: 100px;" @click="dnnDialogConfig.visible = false">{{ t('networkConfig.cancel_label') }}</div>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'dnnConfig',
})
</script>
<script setup  lang="ts">
import { useI18n } from 'vue-i18n'
import { DnnConfigApi } from '@/api/dnnConfig'
import { ElNotificationFn } from '@/utils/computedUtils'
import {cloneDeep} from 'lodash'
import { devinfoApi } from '@/api/devinfo'
import networkAccessManagementBg2 from '@/assets/imgs/networkAccessManagement-bg2.png'
import { BasicConfigApi } from '@/api/basicConfig'
const { t } = useI18n()
const apnConfig = ref<any>({
  apn:'',
  apnId:''
})
const appConfigRef = ref<any>(null)
const appConfigFormRules = ref<any>({
  apn:[
    {required:true,message:'apn不能为空',trigger:'blur'},
  ],
  apnId:[
    {required:true,message:'apnId不能为空',trigger:'blur'},
    {min:1,message:'apnId不能小于1',trigger:'blur'}
  ]
})
const appConfigList = ref<any>([])
async function addApnConfig(){
  try {
    await appConfigRef.value.validate()
    await BasicConfigApi.reqAddApnConfig({
      apn:apnConfig.value.apn,
      id:Number(apnConfig.value.apnId)
    })
    await getDnnList()
    ElNotificationFn('success', t('functionService.add_apn_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.add_apn_failure_label'))
  }
}
async function deleteApnConfig(row:any){
  try {
    await BasicConfigApi.reqDeleteApnConfig({
      apn:row.apn
    })
    await getDnnList()
    ElNotificationFn('success', t('functionService.delete_apn_success_label'))
  } catch (error) {
    ElNotificationFn('error', t('functionService.delete_apn_failure_label'))
  }
}
async function getDnnList(){
  const {data} = await BasicConfigApi.reqGetDnnList()
  appConfigList.value = data.list_get
  apnOptionsConfig.value.options = data.list_get.map((item:any)=>{
    return {
      label:item.apn,
      value:item.apn
    }
  })
}
const TYPE_MAP:any= computed(()=>{
  return {
    internet:t('home.internet_label'),
    private_net:t('home.private_net_label'),
    language:t('home.language_label'),
    xwtj:t('home.xwtj_label'),
    caa:t('home.caa_label'),
  }
})
const apnOptionsConfig = ref<any>({
   options:[],
   width:'200px',
})
const dnnInfoList = ref<any[]>([])
const portList = ref<any[]>([])
async function postDevinfo(){
  const {data} = await devinfoApi.reqPostDevinfo()
  portList.value = data.net_port_list
  getDnnInfoList()
}
async function getDnnInfoList(){
  const {data} = await DnnConfigApi.reqGetDnnInfo()
  dnnInfoList.value = data.list.map((item:any)=>{
    return {
      ...item,
      portList:parsePortMask(item.portmap),
      connectionMode:getConnectionMode(item)
    }
  }).sort((a:any,b:any)=>a.id-b.id)
}
function getConnectionMode(row:any){
  if(row.local_status==='on'){
    return t('networkConfig.local_mode_label')
  }else{
    if(row.nat_status==='on'){
      return t('networkConfig.route_mode_label')
    }else{
      return t('networkConfig.bridge_mode_label')
    }
  }
}
function parsePortMask(mask:any) {
    if (typeof mask === 'string') {
        mask = parseInt(mask, 10); 
        if (isNaN(mask)) {
            console.warn('Invalid decimal mask:', mask);
            return [];
        }
    }
    const ports = [];
    for (let i = 0; i < 32; i++) {
        if (mask & (1 << i)) {
            ports.push(i + 1);
        }
    }
    return ports;
}
const editDnnForm = ref<any>({})
const dnnDialogConfig = ref<any>({
    title:"编辑业务",
    width:"600px",
    visible:false,
})
const editDnnFormRef = ref<any>(null)
const editDnnFormRules = ref<any>({
  vlan_id:[
    { required: true, message: t('networkConfig.vlan_id_required_label'), trigger: 'blur' },
    { 
      type: 'number', 
      message: t('networkConfig.vlan_id_number_label'), 
      trigger: 'blur',
      transform(value: string) {
        if (value === '') return undefined;
        return Number(value);
      } 
    },
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value === '' || value === undefined) return callback();
        const num = Number(value);
        if (isNaN(num)) {
          return callback(new Error(t('networkConfig.vlan_id_number_label')));
        }
        if (num < 1 || num > 4094) {
          return callback(new Error(t('networkConfig.vlan_id_range_label')));
        }
        callback();
      }, 
      trigger: 'blur' 
    }
  ]
})
function handleEditDnn(row:any){
  dnnDialogConfig.value.title = `${t('networkConfig.edit_label')}业务 ${row.id}`
  dnnDialogConfig.value.visible = true
  editDnnForm.value = cloneDeep(row)
}
function setNatDisabled(){
   if(editDnnForm.value.local_status==='on'){
    return true
   }else{
     if(editDnnForm.value.nat_status==='on'||editDnnForm.value.connectionMode===t('networkConfig.route_mode_label')){
      return false
     }else{
      return true
     }
   }
}
// 判断是否为本地模式
function isLocalMode(){
  return editDnnForm.value.local_status === 'on'
}
function convertPortsToMask(ports:any) {
    let mask = 0;
    for (const port of ports) {
        if (typeof port !== 'number' || port < 1 || !Number.isInteger(port)) {
            console.warn(`Invalid port skipped: ${port}`);
            continue;
        }
        const bitPosition = port - 1; 
        mask |= 1 << bitPosition;   
    }
    return mask; 
}
async function saveEditDnn() {
  if (!editDnnFormRef.value) return;
  try {
    await editDnnFormRef.value.validate();
    const portmask = convertPortsToMask(editDnnForm.value.portList)
    const submitData:any = { ...editDnnForm.value }
    submitData.portmap = Number(portmask)
    delete submitData.portList
    await DnnConfigApi.reqSetDnnInfo(submitData)
    ElNotificationFn('success', t('networkConfig.save_success_label'))
    dnnDialogConfig.value.visible = false
    getDnnInfoList()
  } catch (error: any) {
    if (error.message) {
      ElNotificationFn('error', error.message || t('networkConfig.save_error_label'))
    }
  }
}
onMounted(()=>{
  getDnnInfoList()
  getDnnList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/pageLabel.scss';
@import '@/styles/form.scss';
@import '@/styles/table.scss';
@import '@/styles/input.scss';
@import '@/styles/card.scss';
@import '@/styles/switch.scss';
.dnnConfig_container {
  :deep(.el-form-item__label) {
    color: rgba(255, 255, 255, 0.9);
    font-weight: 500;
    text-shadow: 0 0 8px rgba(0, 209, 237, 0.3);
  } 
  :deep(.el-checkbox) {
    --el-checkbox-checked-bg-color: #00D1ED;
    --el-checkbox-checked-input-border-color: #00D1ED;
    --el-checkbox-checked-text-color: rgba(255, 255, 255, 0.9);
    
    &.is-bordered {
      background: rgba(0, 108, 183, 0.15);
      border-color: rgba(0, 209, 237, 0.4);
      border-radius: 4px;
      transition: all 0.3s ease;
      
      &:hover {
        border-color: rgba(0, 209, 237, 0.7);
        box-shadow: 0 0 8px rgba(0, 209, 237, 0.2);
      }
      
      &.is-checked {
        background: rgba(0, 209, 237, 0.15);
        border-color: rgba(0, 209, 237, 0.7);
        box-shadow: 0 0 10px rgba(0, 209, 237, 0.3);
        
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: linear-gradient(45deg, transparent, rgba(0, 209, 237, 0.1), transparent);
          border-radius: 4px;
          animation: checkbox-sweep 2s infinite alternate;
        }
      }
    }
    
    .el-checkbox__label {
      color: rgba(255, 255, 255, 0.9);
    }
  }
}

@keyframes checkbox-sweep {
  0% {
    opacity: 0;
    background-position: -100% 0;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 0;
    background-position: 200% 0;
  }
}
</style>
